<template>
    <breadCrumb ref="breadcrumb" :item="item"></breadCrumb>
    <div class="common-wrapped">
        <div class="common-content">
            <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane label="账号详情" name="first">
                    <div class="account-info-wrapped">
                        <span>用户头像:</span>
                        <div class="account-info-content">
                            <!-- action上传头像的接口 -->
                            <!-- show-file-list展示上传文件列表 -->
                            <el-upload class="avatar-uploader" action="http://127.0.0.1:3030/user/uploadAvatar"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="userStore.imageUrl" :src="userStore.imageUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户账号:</span>
                        <div class="account-info-content">
                            <el-input v-model="userStore.account" disabled></el-input>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户密码:</span>
                        <div class="account-info-content">
                            <el-button type="primary" plain @click="ModifyPassword.open()">修改密码</el-button>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户姓名:</span>
                        <div class="account-info-content">
                            <el-input v-model="userStore.name"></el-input>
                        </div>
                        <el-button type="primary" @click="modifyName">保存</el-button>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户性别:</span>
                        <div class="account-info-content">
                            <el-select v-model="userStore.sex" placeholder="请选择性别">
                                <el-option label="男" value="男" />
                                <el-option label="女" value="女" />
                            </el-select>
                        </div>
                        <el-button type="primary" @click="modifySex">保存</el-button>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户身份:</span>
                        <div class="account-info-content">
                            <el-input v-model="userStore.identity" disabled></el-input>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户部门:</span>
                        <div class="account-info-content">
                            <el-input v-model="userStore.department" disabled></el-input>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>用户邮箱:</span>
                        <div class="account-info-content">
                            <el-input v-model="userStore.email"></el-input>
                        </div>
                        <el-button type="primary" @click="modifyEmail">保存</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="相关信息" name="second" v-if="userStore.identity == '超级管理员'">
                    <div class="account-info-wrapped">
                        <span>奖学金相关政策:</span>
                        <div class="account-info-content">
                            <el-button type="success" plain @click="openEditor(1)">编辑</el-button>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>奖学金申请通告:</span>
                        <div class="account-info-content">
                            <el-button type="success" plain @click="openEditor(2)">编辑</el-button>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>助学金相关政策:</span>
                        <div class="account-info-content">
                            <el-button type="success" plain @click="openEditor(3)">编辑</el-button>
                        </div>
                    </div>
                    <div class="account-info-wrapped">
                        <span>助学金申请通告:</span>
                        <div class="account-info-content">
                            <el-button type="success" plain @click="openEditor(4)">编辑</el-button>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="首页管理" name="third" v-if="userStore.identity == '超级管理员'">
                    <div class="home-wrapped">
                        <div class="tips">
                            <span>
                                提示:点击图片框进行切换首页轮播图
                            </span>
                        </div>
                        <div class="swiper-wrapped" v-for="(item, index) in swiperData" :key="index">
                            <div class="swiper-name">
                                {{ item.name }}:&nbsp;&nbsp;
                            </div>
                            <el-upload class="avatar-uploader" action="http://127.0.0.1:3030/setting/uploadSwiper"
                                :show-file-list="false" :on-success="handleSwiperSuccess" :data="item">
                                <template #trigger>
                                    <img v-if="imageUrl[index]" :src="imageUrl[index]" class="swiper" />
                                    <SvgIcon icon-name="uploadSwiper" v-else :size="size"></SvgIcon>
                                </template>
                            </el-upload>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="其他设置" name="fourth" v-if="userStore.identity == '超级管理员'">
                    <div class="other-set">
                        <div class="department-set">
                            <span>部门设置</span>
                            <el-tag v-for="tag in dynamicTags" :key="tag" class="mx-1" closable
                                :disable-transitions="false" @close="handleClose(tag)">
                                {{ tag }}
                            </el-tag>
                            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue"
                                class="ml-1 w-20 departmentInput" size="small" @keyup.enter="handleInputConfirm"
                                @blur="handleInputConfirm" />
                            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                                + 添加部门
                            </el-button>
                        </div>
                        <div class="product-set">
							<span>院系设置</span>
							<el-tag v-for="tag in dynamicCollegeTags" :key="tag" class="mx-1" closable
								:disable-transitions="false" @close="handleCollegeClose(tag)">
								{{ tag }}
							</el-tag>
							<el-input v-if="inputCollegeVisible" ref="InputCollegeRef" v-model="inputCollegeValue" class="ml-1 w-20 collegeInput"
								size="small" @keyup.enter="handleInputCollegeConfirm" @blur="handleInputCollegeConfirm" />
							<el-button v-else class="button-new-tag ml-1" size="small" @click="showCollegeInput">
								+ 添加院系
							</el-button>
						</div>
                        <!-- <div class="product-set">
							<span>产品设置</span>
							<el-tag v-for="tag in dynamicProductTags" :key="tag" class="mx-1" closable
								:disable-transitions="false" @close="handleProductClose(tag)">
								{{ tag }}
							</el-tag>
							<el-input v-if="inputProductVisible" ref="InputProductRef" v-model="inputProductValue" class="ml-1 w-20"
								size="small" @keyup.enter="handleInputProductConfirm" @blur="handleInputProductConfirm" />
							<el-button v-else class="button-new-tag ml-1" size="small" @click="showProductInput">
								+ 添加产品
							</el-button>
						</div> -->
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
    <modifyPassword ref="ModifyPassword"></modifyPassword>
    <editor ref="Editor"></editor>
</template>

<script lang="ts" setup>
import breadCrumb from '@/components/BreadCrumb.vue';
import { ref, nextTick, toRaw } from 'vue';
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useUserInfoStore } from '@/store/userInfo.js'
import { bindAccount, changeEmail, changeName, changeSex } from '@/api/userInfo.js'
import modifyPassword from './component/modifyPassword.vue'
import editor from './component/editor.vue';
import { bus } from "@/utils/mitt.js"
import SvgIcon from '@/components/svgIcon.vue'
import { getAllSwiper, getDepartment, setDepartment,getCollege,setCollege } from '@/api/setting.js'

//修改密码弹窗
const ModifyPassword = ref()
//用户信息存储
const userStore = useUserInfoStore()
//面包屑
const breadcrumb = ref()
const item = ref({
    first: '系统设置',
})
//默认打开的标签页
const activeName = ref('first')

//头像上传成功以后绑定账号
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
) => {
    if (response.status === 0) {
        //头像上传成功,更新本地存储最新头像地址
        userStore.imageUrl = response.url
        ElMessage.success('头像上传成功!'),
            (async () => {
                await bindAccount(userStore.account, response.onlyId, response.url)
            })()
    } else {
        ElMessage.error('头像上传失败!')
    }
}
//头像上传之前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('头像必须是JPG格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像必须小于 2MB!')
        return false
    }
    return true
}
//修改姓名
const modifyName = async () => {
    //因为输入框和本地存储相关内容绑定,一旦修改本地内容就会修改
    const res = await changeName(userStore.id, userStore.name)
    console.log(res)
    if (res.data.status === 0) {
        ElMessage.success('修改姓名成功!')
    } else {
        ElMessage.error(res.data.message)
    }
}
//修改性别
const modifySex = async () => {
    //因为输入框和本地存储相关内容绑定,一旦修改本地内容就会修改
    const res = await changeSex(userStore.id, userStore.sex)
    if (res.data.status === 0) {
        ElMessage.success('修改性别成功!')
    } else {
        ElMessage.error('修改性别失败!')
    }
}
//修改邮箱
const modifyEmail = async () => {
    //因为输入框和本地存储相关内容绑定,一旦修改本地内容就会修改
    const res = await changeEmail(userStore.id, userStore.email)
    if (res.data.status === 0) {
        ElMessage.success('修改邮箱成功!')
    } else {
        ElMessage.error(res.data.message)
    }
}

//富文本编辑器
const Editor = ref()
//打开富文本编辑器
const openEditor = (id: number) => {
    //第一个参数是标记,第二个参数是标题
    bus.emit('editorTitle', id)
    Editor.value.open()
}
//上传轮播图成功
const size = ref(100)
const swiperData = [
    { name: 'swiper1' },
    { name: 'swiper2' },
    { name: 'swiper3' },
    { name: 'swiper4' },
]
const imageUrl = ref('')
const handleSwiperSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.status === 0) {
        ElMessage.success('轮播图上传成功!')
        getAllSwiperData()
    } else {
        ElMessage.error('轮播图上传失败!')
    }
}
//获取所有轮播图
const getAllSwiperData = async () => {
    const res = await getAllSwiper()
    imageUrl.value = res.data
}
getAllSwiperData()
// 其他设置
// setDepartment
// getDepartment
// 部门设置
const inputValue = ref('')
const dynamicTags = ref()
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
// 院系设置
const inputCollegeValue = ref('')
const dynamicCollegeTags = ref()
const inputCollegeVisible = ref(false)
const InputCollegeRef = ref<InstanceType<typeof ElInput>>()
// 产品设置
// const inputProductValue = ref('')
// const dynamicProductTags = ref()
// const inputProductVisible = ref(false)
// const InputProductRef = ref<InstanceType<typeof ElInput>>()
// 获取部门数据
const returnDepartment = async () => {
    const res = await getDepartment()
    dynamicTags.value = res.data
}
returnDepartment()
// 获取院系数据
const returnCollege = async () => {
    const res = await getCollege()
    dynamicCollegeTags.value = res.data
}
returnCollege()
// 获取产品数据
// const returnProduct = async () => {
//     dynamicProductTags.value = await getProduct()
// }
// returnProduct()
// 部门设置关闭时的函数
const handleClose = async (tag: string) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
    const res = await setDepartment(JSON.stringify(toRaw(dynamicTags.value)))
    if (res.data.status === 0) {
        ElMessage({
            message: '删除部门成功',
            type: 'success',
        })
    } else {
        ElMessage.error('删除部门失败，请重新输入！')
    }
}
// 院系设置关闭时的函数
const handleCollegeClose = async (tag: string) => {
    dynamicCollegeTags.value.splice(dynamicCollegeTags.value.indexOf(tag), 1)
    const res = await setCollege(JSON.stringify(toRaw(dynamicCollegeTags.value)))
    if (res.data.status === 0) {
        ElMessage({
            message: '删除院系成功',
            type: 'success',
        })
    } else {
        ElMessage.error('删除院系失败，请重新输入！')
    }
}
// 产品设置关闭时的函数
// const handleProductClose = async (tag: string) => {
//     dynamicProductTags.value.splice(dynamicProductTags.value.indexOf(tag), 1)
//     const res = await setProduct(JSON.stringify(toRaw(dynamicProductTags.value)))
//     if (res.data.status === 0) {
//         ElMessage({
//             message: '删除产品成功',
//             type: 'success',
//         })
//     } else {
//         ElMessage.error('删除产品失败，请重新输入！')
//     }
// }
// 点击部门按钮出现输入框
const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
// 点击院系按钮出现输入框
const showCollegeInput = () => {
    inputCollegeVisible.value = true
    nextTick(() => {
        InputCollegeRef.value!.input!.focus()
    })
}
// 点击产品按钮出现输入框
// const showProductInput = () => {
//     inputProductVisible.value = true
//     nextTick(() => {
//         InputProductRef.value!.input!.focus()
//     })
// }
// 输入数据后的一个函数 部门
const handleInputConfirm = async () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
        const res = await setDepartment(JSON.stringify(toRaw(dynamicTags.value)))
        if (res.data.status == 0) {
            ElMessage({
                message: '添加部门设置成功',
                type: 'success',
            })
        } else {
            ElMessage.error('添加部门失败，请重新输入！')
        }
    }
    inputVisible.value = false
    inputValue.value = ''
}
// 输入数据后的一个函数 院系
const handleInputCollegeConfirm = async () => {
    if (inputCollegeValue.value) {
        console.log(dynamicCollegeTags.value)
        dynamicCollegeTags.value.push(inputCollegeValue.value)
        const res = await setCollege(JSON.stringify(toRaw(dynamicCollegeTags.value)))
        if (res.data.status == 0) {
            ElMessage({
                message: '添加院系设置成功',
                type: 'success',
            })
        } else {
            ElMessage.error('添加院系失败，请重新输入！')
        }
    }
    inputCollegeVisible.value = false
    inputCollegeValue.value = ''
}
// 输入数据后的一个函数 产品
// const handleInputProductConfirm = async () => {
//     if (inputProductValue.value) {
//         dynamicProductTags.value.push(inputProductValue.value)
//         const res = await setProduct(JSON.stringify(toRaw(dynamicProductTags.value)))
//         if (res.status == 0) {
//             ElMessage({
//                 message: '添加产品设置成功',
//                 type: 'success',
//             })
//         } else {
//             ElMessage.error('添加产品失败，请重新输入！')
//         }
//     }
//     inputProductVisible.value = false
//     inputProductValue.value = ''
// }
</script>

<style lang="scss" scoped>
.common-wrapped {
    padding: 8px;
    background: #f5f5f5;
    height: calc(100vh - 101px);

    .common-content {
        padding: 0 10px;
        height: 100%;
        background: #fff;

        .account-info-wrapped {
            display: flex;
            align-items: center;
            padding-left: 50px;
            margin-bottom: 18px;
            font-size: 14px;

            .account-info-content {
                width: 178px;
                margin-left: 24px;
                margin-right: 16px;
            }
        }

        //首页管理外壳
        .home-wrapped {
            padding-left: 50px;
            display: flex;
            flex-direction: column;

            .tips {
                display: flex;
                align-items: center;
                margin-bottom: 8px;

                span {
                    font-size: 14px;
                    color: silver;
                }
            }

            .swiper-wrapped {
                display: flex;
                margin-bottom: 16px;

                .swiper-name {
                    font-size: 14px;
                    margin-bottom: 24px;
                }

                .swiper {
                    width: 336px;
                    height: 96px;
                }
            }
        }
    }
}

// 其他设置
.other-set {
    padding-left: 50px;
    font-size: 14px;

    .department-set {
        margin-bottom: 24px;

        span {
            margin-right: 24px;
        }
    }

    .product-set {

        span {
            margin-right: 24px;
        }
    }
}

//标签页
.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

//上传头像
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.departmentInput {
    width: 240px;
}
.collegeInput {
    width: 240px;
}
.productInput {
    width: 240px;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
